package com.retry.task.datasource.core;

import java.util.ArrayList;
import java.util.List;

import com.retry.task.datasource.annotation.MultiMapper;
import com.retry.task.datasource.annotation.MultiMapperScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

public class MultiMapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
    private ResourceLoader resourceLoader;

    public MultiMapperScannerRegistrar() {
    }

    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MultiMapperScan.class.getName()));
        MultiClassPathMapperScanner scanner = new MultiClassPathMapperScanner(registry);
        if (this.resourceLoader != null) {
            scanner.setResourceLoader(this.resourceLoader);
        }

        scanner.setAnnotationClass(MultiMapper.class);
        Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator");
        if (!BeanNameGenerator.class.equals(generatorClass)) {
            scanner.setBeanNameGenerator((BeanNameGenerator)BeanUtils.instantiateClass(generatorClass));
        }

        List<String> basePackages = new ArrayList();
        String[] pkgArr = annoAttrs.getStringArray("value");
        int pkgLength = pkgArr.length;

        int num;
        String pkg;
        for(num = 0; num < pkgLength; ++num) {
            pkg = pkgArr[num];
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }

        pkgArr = annoAttrs.getStringArray("basePackages");
        pkgLength = pkgArr.length;

        for(num = 0; num < pkgLength; ++num) {
            pkg = pkgArr[num];
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }

        Class[] basePackArr = annoAttrs.getClassArray("basePackageClasses");
        pkgLength = basePackArr.length;

        for(num = 0; num < pkgLength; ++num) {
            Class<?> clazz = basePackArr[num];
            basePackages.add(ClassUtils.getPackageName(clazz));
        }

        scanner.registerFilters();
        scanner.doScan(StringUtils.toStringArray(basePackages));
    }

    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
}